import { onMounted, onUnmounted } from 'vue'
import _ from 'lodash'

interface IOption {
  targetX: number
  targetY: number
  targetRatio: number
}

// 大屏适配
function triggerScale(option: IOption) {
  const targetX = option.targetX || 1920
  const targetY = option.targetY || 1080
  const targetRatio = option.targetRatio || 16 / 9 // 宽高比

  // 拿到当前设备(浏览器)的宽度
  const currentX = document.documentElement.clientWidth || document.body.clientWidth // 获取当前设备(浏览器)的宽度
  const currentY = document.documentElement.clientHeight || document.body.clientHeight // 获取当前设备(浏览器)的高度

  // 计算缩放比例
  let scaleRatio = currentX / targetX // 当前设备宽度 / 目标宽度
  const currentRatio = currentX / currentY // 当前设备宽高比

  if (currentRatio > targetRatio) {
    // 参照高度进行缩放
    scaleRatio = currentY / targetY
    document.body.style.width = `${targetX}px;`
    document.body.style.height = `${targetY}px;`
    document.body.style.transform = `scale(${scaleRatio}) translateX(-50%);`
    document.body.style.left = '50%;'
  } else {
    // 参照宽度进行缩放
    document.body.style.width = `${targetX}px`
    document.body.style.height = `${targetY}px`
    document.body.style.transform = `scale(${scaleRatio})`
  }
}
function useScalePage(option: IOption) {
  const resizeFunc = _.throttle(() => {
    triggerScale(option) // 触发缩放
  }, 100)

  onMounted(() => {
    triggerScale(option) // 动画缩放网页
    window.addEventListener('resize', resizeFunc)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resizeFunc)
  })
}

export default useScalePage
